package com.ruoyi.common.utils.http;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestTemplate;

import org.springframework.http.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RestTemplateUtil {
    private static final Logger logger = LoggerFactory.getLogger(RestTemplateUtil.class);
    // 初始化RestTemplate并配置超时
    private static RestTemplate restTemplate = createRestTemplate();

    private static RestTemplate createRestTemplate() {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        // 连接超时设置为5秒
        requestFactory.setConnectTimeout(300000);
        // 读取超时设置为10秒
        requestFactory.setReadTimeout(300000);
        return new RestTemplate(requestFactory);
    }
    /**
     * 发送POST请求到指定URL
     * @param url 请求URL
     * @param jsonData 请求体JSON字符串
     * @return 响应结果字符串
     * @throws Exception 处理过程中的异常
     */
    public static String sendPost(String url, String jsonData) throws Exception {
        // 验证参数
        if (url == null || url.trim().isEmpty()) {
            throw new IllegalArgumentException("请求URL不能为空");
        }
        if (jsonData == null) {
            throw new IllegalArgumentException("请求数据不能为空");
        }

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        // 可以根据需要添加其他头信息
//         headers.add("Authorization", "Bearer your_token");
         headers.add("Content-Type","application/json");
        // 封装请求实体
        HttpEntity<String> requestEntity = new HttpEntity<>(jsonData, headers);
        try {
            // 发送POST请求
            ResponseEntity<String> response = restTemplate.exchange(
                    url,
                    HttpMethod.POST,
                    requestEntity,
                    String.class
            );
            // 处理响应
            if (response.getStatusCode().is2xxSuccessful()) {
                return response.getBody();
            } else {
                throw new Exception("请求失败，状态码: " + response.getStatusCodeValue());
            }
        } catch (HttpStatusCodeException e) {
            // 处理HTTP状态异常
            String errorMsg = String.format(
                    "HTTP请求异常，状态码: %d，响应内容: %s",
                    e.getRawStatusCode(),
                    e.getResponseBodyAsString()
            );
            throw new Exception(errorMsg, e);
        } catch (Exception e) {
            // 处理其他异常
            throw new Exception("发送POST请求失败: " + e.getMessage(), e);
        }
    }

    public static void main(String[] args) {
        // 测试示例
        String url = "http://1.12.43.211:8000/dify/chatflow-ypj/report";
        String data = "{\n" + "  \"houses_id\": \"11287\"\n" + "}";
        try {
            String result = sendPost(url, data);
            logger.info("请求成功，响应结果: " + result);
            // 解析 JSON 字符串
            JSONObject jsonObject = JSON.parseObject(result);
            // 获取 data 数组
            JSONArray dataArray = jsonObject.getJSONArray("data");
            JSONObject targetData = null;
            // 遍历数组，找到 type="data" 的对象
            for (int i = 0; i < dataArray.size(); i++) {
                JSONObject obj = dataArray.getJSONObject(i);
                if ("data".equals(obj.getString("type"))) {
                    // 获取红框中的 data 数据
                    targetData = obj.getJSONObject("data").getJSONObject("data");
                    break;
                }
            }
            if (targetData != null) {
                // 将获取到的 data 转成 JSON 字符串
                String targetJson = targetData.toJSONString();
                System.out.println(targetJson);
            } else {
                System.out.println("未找到 type=\"data\" 的数据");
            }
        } catch (Exception e) {
            logger.error("请求失败: " + e.getMessage());
            e.printStackTrace();
        }

    }
}
